package cn.itcast.mq.listener;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Xiao
 * @version 1.0
 * @description 消息监听器
 * @date 2021/11/19
 */
@Slf4j
@Component
public class SpringRabbitListener {
    private static final String SIMPLE_QUEUE = "simple.queue";
    private static Integer count = 1;

    /***
     * 监听simple.queue队列的消息
     * @param msg
     */
    @RabbitListener(queues = SIMPLE_QUEUE)
    public void listenSimpleQueue(String msg) {
        System.out.println("消费者接收到simple.queue的消息：【" + msg + "】");
        String time = new SimpleDateFormat("HH:mm:ss").format(new Date());
        System.out.println("当前时间：" + time + "，此次为第" + count++ + "次发送" );
        System.out.println(1 / 0);  //模拟异常
        log.debug("消息处理完成。。。");
    }

    private static final String ERROR_QUEUE = "error.queue";

    /**
     * 监听error.queue队列的消息
     * @param msg
     */
    @RabbitListener(queues = ERROR_QUEUE)
    public void listenErrorQueue(String msg) {
        System.err.println("消费者接收到error.queue的消息：【" + msg + "】");
        //业务逻辑
        count = 1;
    }

    private static final String DL_EXCHANGE = "dl.direct";
    private static final String DL_QUEUE = "dl.queue";
    private static final String DL_TEST_KEY = "dl.test";
    /**
     * 监听死信队列消息
     * @param msg
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = DL_QUEUE, durable = "true"),
            exchange = @Exchange(name = DL_EXCHANGE),
            key = DL_TEST_KEY
    ))
    public void listenDlQueue(String msg) {
        log.debug("消息接收成功！");
        System.err.println("消费者接收到dl.queue的消息：【" + msg + "】");
    }

    private static final String DELAY_EXCHANGE = "delay.direct";
    private static final String DELAY_QUEUE = "delay.queue";
    private static final String DELAY_TEST_KEY = "delay.test";
    /**
     * 监听延迟消息
     * @param msg
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = DELAY_QUEUE, durable = "true"),
            exchange = @Exchange(name = DELAY_EXCHANGE, delayed = "true"),
            key = DELAY_TEST_KEY
    ))
    public void listenDelayQueue(String msg) {
        System.err.println("消费者接收到delay.queue的消息：【" + msg + "】");
        log.debug("消息接收成功！");
    }
}
